package SA.Gms.Ui.Util;
import java.awt.AWTException;
import java.awt.Robot;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.ErrorHandler.UnknownServerException;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import Recorder.Recorder;


public class BrowserSetup {
	
	
	public static WebDriver driver;
	public WebElement element,eventElement;
	public static String logMessage="";
	PrintWriter log = null,log1;
	public static File directory = new File (".");
	public static int ie=0;
	public String Elementtype=null,tagName=null;
	public BrowserSetup(String DriverPath,String BrowserName)
	{
		
		if(BrowserName!=null)
		{
			
		if(BrowserName.equalsIgnoreCase("Chrome") && DriverPath!=null)
		{
			System.out.print("Browser Name :"+BrowserName);
			DriverPath=DriverPath+"chromedriver.exe";
			this.driver = getChrome(DriverPath);
			
			//launchUrl(Url);
			
		}
		else if(BrowserName.equalsIgnoreCase("IE") && DriverPath!=null)
		{
			System.out.print("Browser Name :"+BrowserName);
			ie=1;
			DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
			capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
			 /*capabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, false);*/
			DriverPath=DriverPath+"IEDriverServer.exe";
			this.driver = getie(DriverPath,capabilities);
			
			
			//launchUrl(Url);
			
		}
		else if(BrowserName.equalsIgnoreCase("FireFox")||BrowserName.equalsIgnoreCase("FF")||BrowserName.equalsIgnoreCase("mozilla"))
		{
			System.out.print("Browser Name :"+BrowserName);
			this.driver = getFireFox();
			
			
			//launchUrl(Url);
			
		}
		else
		{
			System.out.print("Warning !! Invalid Browser Name Specified..\n Working with Default Setting\nBrowser Name :FireFox");
			this.driver = getFireFox();
		}
		
			
		}else
		{
			System.out.print("Warning !! Browser Name is Not Specified..\n Working with Default Setting\nBrowser Name :FireFox");
			this.driver = getFireFox();
		}
	}
	public BrowserSetup() {
		// TODO Auto-generated constructor stub
	}
	public String launchStep(String framexpath,String eventid,String eventname,String eventxpath,String action,String actionvalue)
	{
		
		int flag=0;
		log1=ReadTestSuite.log1;
		try{
			if(action.equalsIgnoreCase("getinfo"))
			{
				if(ReadTestCase.PageValidationTitle==null)
				{
					System.out.print("Click the Event to get info about that event");
				}
				else{

					try {
						if(!new File(directory.getCanonicalPath()+"\\logs").isDirectory())
						{
							new File(directory.getCanonicalPath()+"\\logs").mkdirs();
						}
						log = new PrintWriter(new File(ReadTestSuite.testSuitePath+"\\logs\\"+ReadTestCase.PageValidationTitle+new Date().toString().replaceAll(":", "-")+".properties"));
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						return "Error";
					} catch (IOException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
						return "Error";
					}
					writegetInfo();
						
				}
			}
			else
				if(action.equalsIgnoreCase("Validate"))
				{
					if(ReadTestCase.PageValidationTitle==null)
					{
						System.out.print("Click the Event to get info about that event");
					}
					else{

						String dir=directory.getCanonicalPath()+File.separator+"Suites"+File.separator+ReadTestSuite.Suitename+"\\Validation\\";
						new ValidateTestcase().validateTc(dir+ReadTestCase.XlName,ReadTestCase.TcName ,dir+ReadTestCase.PageValidationTitle+".properties");
						
						if(ValidateTestcase.TestRecordFound==0)
						{
							log1.println("Test Case Expected Results Doestn't Exist in the Excel  : "+ReadTestCase.TcName);
							System.out.println("Test Case Expected Result Doestn't Exist for TestCase : "+ReadTestCase.TcName);
						}
						else
						{
							log1.println(logMessage);	
							System.out.println(logMessage);
						}
						
							
					}
				}
				else if(action.equalsIgnoreCase("Record"))
				{
					
					if(ReadTestCase.PageValidationTitle==null)
					{
						System.out.print("Specify Start/Stop for Recording");
					}
					else
					{
						if(ReadTestCase.PageValidationTitle.equalsIgnoreCase("Start"))
								{
							Recorder.startRecording();
								}
						else if(ReadTestCase.PageValidationTitle.equalsIgnoreCase("Stop"))
						{
							Recorder.stopRecording(ReadTestCase.TcName+"_");
						}
						else if(ReadTestCase.PageValidationTitle.equalsIgnoreCase("capture"))
						{
							Recorder.Screencapture(ReadTestCase.StepName+"_");
						}
						else{
							System.out.print("invalida parameter for Recoder");
						}
					}
					
				}
				else if(action.equalsIgnoreCase("wait"))
				{
					
					if(ReadTestCase.waitmin==0)
					{
						waittoload();
					}
					else
					{
						waittoload(ReadTestCase.waitmin);
					}
					
				}
			
				else if(action.equalsIgnoreCase("InspectPage"))
				{
					if(ReadTestCase.PageValidationTitle==null)
					{
						ReadTestCase.PageValidationTitle="";
						System.out.print("Warning !! Page Name is Missing in the Step ");
						InspectPage(ReadTestCase.PageValidationTitle);
					}
					else
					{
						InspectPage(ReadTestCase.PageValidationTitle);
					}
					
					
				}
			else
			{
			waittoload();
			if(framexpath!=null && framexpath!="" && framexpath!=" ")
			{
				launchPageByXpath(framexpath);
			}
			if(eventid!=null  && eventid!="" && eventid!=" ")
			{
				launchEventById(eventid);
				flag=1;
			}
			else if(eventname!=null  && eventname!="" && eventname!=" ")
			{
				launchEventByName(eventname);	
				flag=2;
			}
			else  if(eventxpath!=null  && eventxpath!="" && eventxpath!=" ")
			{
				launchEventByXpath(eventxpath);	
				flag=3;
			}
			
			if(action.equalsIgnoreCase("click"))
			{
				
				if(Elementtype==null)
					{
					clickElement(eventElement);
					System.out.println("Warning!! clicking HyperLink ");
					}
				else if(Elementtype.equalsIgnoreCase("checkbox"))
				clickElement(eventElement);
				else if(Elementtype.equalsIgnoreCase("radio"))
					clickElement(eventElement);
				else if(Elementtype.equalsIgnoreCase("submit"))
					clickElement(eventElement);
				else
				{
					clickElement(eventElement);
					System.out.println("Error Invalid action,please specify Click event for Checkbox/radio/submit button");
					return "failed";
				}
					
					
			}
			else if(action.equalsIgnoreCase("sendKey"))
			{
				if(Elementtype.equalsIgnoreCase("text"))
				{
				sendElementValue(eventElement,actionvalue);
				}
				else
				{
					System.out.println("sendKey is an invalid action, please specify Exact event");
					return "failed";
				}
			}
			else if(action.equalsIgnoreCase("selectdropdown"))
			{
				if(tagName.equalsIgnoreCase("select"))
				{
					selectDropdown(eventElement,actionvalue);
				}
				else
				{
					System.out.println("selectdropdown ia an invalid action,please specify Exact event ");
					return "failed";
				}
				
			}
			else
			{
				System.out.println(action +" : invalid action, Not Found in Command Library" );
				return "failed";
			}
			}
			//exitTestcase(this.driver);
		}
		catch(UnhandledAlertException ua)
		{
			//AlertClick();
			
		}
		
		catch(Exception e)
		{
			e.printStackTrace();
			return "error";
		}
		
		return "Passed";
		
	}
	
	public void exitTestcase()
	{
		this.driver.quit();
	}
	
	public WebDriver getChrome(String path)
	{
		System.setProperty("webdriver.chrome.driver", path);
		WebDriver cdriver = new ChromeDriver();
		
		return cdriver;
	}
	public WebDriver getie(String path,DesiredCapabilities capabilities)
	{
		System.setProperty("webdriver.ie.driver", path);
		WebDriver cdriver = new InternetExplorerDriver(capabilities);
		
		return cdriver;
	}
	public WebDriver getFireFox()
	{
	/*	FirefoxProfile fp = new FirefoxProfile();
		   fp.setPreference("webdriver.load.strategy", "unstable");*/
		WebDriver cdriver = new FirefoxDriver();
		
		return cdriver;
	}
	public void launchUrl(String Url)
	{
		if(ie==1)
		{
		
		driver.get(Url);
		driver.navigate().to("javascript:document.getElementById('overridelink').click()");	
		ie++;
		}
		else
		{
			driver.get(Url);
		}
		waittoload();
		
	}
	public void launchEventById(String Id)
	{
		
		this.eventElement=getElementById(Id);
		
	}
	public void launchEventByName(String Name)
	{
		
		this.eventElement=getElementByName(Name);
		
	}
	public void launchEventByXpath(String Xpath)
	{
		
		this.eventElement=getElementByXpath(Xpath);
		
	}
	public void launchPageById(String Id)
	{
		switchDefaultElement();
		this.element=getElementById(Id);
		switchElement(this.element);
	}
	public void launchPageByName(String Name)
	{
		switchDefaultElement();
		this.element=getElementByName(Name);
		switchElement(this.element);
	}
	public void launchPageByXpath(String Xpath)
	{
		switchDefaultElement();
		this.element=getElementByXpath(Xpath);
		switchElement(this.element);		
	}
	public void waittoload()
	{
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	}
	public void waittoload(int time)
	{
		try {
			Thread.sleep(time*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void switchElement(WebElement switchElement)
	{
		driver.switchTo().frame(switchElement);
		System.out.println("Frame");
		
	}
	public void switchDefaultElement()
	{		
		driver.switchTo().defaultContent();
	}
	public void AlertClick()
	{
		try {
	        (new Robot()).keyPress(java.awt.event.KeyEvent.VK_ENTER);

	         (new Robot()).keyRelease(java.awt.event.KeyEvent.VK_ENTER);
	         } catch (AWTException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	
	}
	public void checkAlert() {
	    try {
	        WebDriverWait wait = new WebDriverWait(driver, 2);
	        wait.until(ExpectedConditions.alertIsPresent());
	        Alert alert = driver.switchTo().alert();
	        alert.accept();
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}
	public WebElement getElementById(String id)
	{
		element = driver.findElement(By.id(id));
		Elementtype=element.getAttribute("type");
		tagName=element.getTagName();
		return element;		
	}
	public WebElement getElementByName(String name)
	{
		element = driver.findElement(By.name(name));
		return element;		
	}
	public WebElement getElementByXpath(String xpath)
	{
		element = driver.findElement(By.xpath(xpath));
		return element;		
	}
	public void clickElement(WebElement clickElement)
	{
		clickElement.click();
		Object executeScript = ((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
		waittoload();
	}
	public void submitElement(WebElement submitElement)
	{
		submitElement.submit();
		waittoload();
	}
	public void sendElementValue(WebElement sendElement,String value )
	{
		sendElement.clear();
		sendElement.sendKeys(value);
	}
	public void clearElementValue(WebElement clearElement)
	{
		clearElement.clear();
	}
	public void selectDropdown(WebElement dropdownElement ,String visibletext )
	{
		Select option=new Select(dropdownElement);
		option.selectByVisibleText(visibletext);
	}
	public void writegetInfo()
	{
		List<WebElement> outputText2= driver.findElements(By.className("outputText"));  
		//System.out.println(input.size());
		
		for(int i=0;i<outputText2.size();i++)
		{

			// System.out.println(input.get(i).getAttribute("id"));
			if(outputText2.get(i).getAttribute("style").isEmpty() )
			{

				if(!outputText2.get(i).getAttribute("id").isEmpty())
				{
				log.print(outputText2.get(i).getAttribute("id")+"=");
				log.println(outputText2.get(i).getText());
				}

			}

		}
		
		log.close();
	}
	public static String getInfo(String FormId)
	{
		try
		{
		WebElement outputValue= driver.findElement(By.id(FormId));  
		return outputValue.getText();
		}
		catch(NoSuchElementException e)
		{
			System.out.println(e.getMessage());
			return "Error";			
		}
		catch(NullPointerException e)
		{
			System.out.println(e.getMessage());
			return "Error";			
		}
	}
	public static void InspectPage(String pageName)
	{
		String concatStepName="",concatStepValue="";
		PrintWriter logTemplate = null;
		try{
			
			try {
				logTemplate = new PrintWriter(new File(ReadTestSuite.testSuitePath+"/logs/"+"\\Template_"+pageName+"_"+new Date().toString().replaceAll(":", "-")+".xml"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			logTemplate.print("<TestCase>");
		List<WebElement>  input= driver.findElements(By.tagName("input"));  
		for(int i=0;i<input.size();i++)
		{

			if(!input.get(i).getAttribute("type").equalsIgnoreCase("hidden")&& input.get(i).getAttribute("type").equalsIgnoreCase("text"))
			{
				
				if(input.get(i).getAttribute("tabindex")==null)
				{
				String id=input.get(i).getAttribute("id");
				String stepName=id.replaceAll("[\',/'-+.^:,]", "_");
				concatStepName+=stepName+"|";
				String Action=stepName+"_Action";
				concatStepName+=Action+"|";
				concatStepValue+=id+"|";
				concatStepValue+="|";
				logTemplate.print("<Step Name=\"");
				logTemplate.print(stepName);
				logTemplate.print("\">\n<param  Name=\"FrameSrc\"></param>\n<param  Name=\"FindElementById\">");
				logTemplate.print(id);
				logTemplate.print("</param>\n");
				//logTemplate.print("<param  Name=\"FindElementByName\"/> 		<param  Name=\"FindElementByXpath\"/> ");
				logTemplate.print("		<param  Name=\"Action\" event=\"sendKey\">");
				logTemplate.print(Action);
				logTemplate.print("</param> 	</Step>");
				/*
				log.print("\t"+input.get(i).getAttribute("name"));
				log.println("\t"+input.get(i).getAttribute("size"));
				*/
				}
			}
			if(!input.get(i).getAttribute("type").equalsIgnoreCase("hidden")&& (input.get(i).getAttribute("type").equalsIgnoreCase("radio")||input.get(i).getAttribute("type").equalsIgnoreCase("checkbox")))
			{
				
				String id=input.get(i).getAttribute("id");
				String stepName=id.replaceAll("[\',/'-+.^:,]", "_");
				concatStepName+=stepName+"|";
				String Action=stepName+"_Action";
				concatStepName+=Action+"|";
				concatStepValue+=id+"|";
				concatStepValue+="|";
				logTemplate.print("<Step Name=\"");
				logTemplate.print(stepName);
				logTemplate.print("\">\n<param  Name=\"FrameSrc\"></param>\n<param  Name=\"FindElementById\">");
				logTemplate.print(id);
				logTemplate.print("</param>\n");
				//logTemplate.print("<param  Name=\"FindElementByName\"/> 		<param  Name=\"FindElementByXpath\"/> ");
				logTemplate.print("		<param  Name=\"Action\" event=\"click\"/>	</Step>");
				
				/*
				log.print("\t"+input.get(i).getAttribute("name"));
				log.println("\t"+input.get(i).getAttribute("size"));
				*/
				
			}

		}
		input= driver.findElements(By.tagName("select"));  
		System.out.println(input.size());
		//log.println("DropDown Box");
		
		for(int i=0;i<input.size();i++)
		{

			// System.out.println(input.get(i).getAttribute("id"));
			if(!input.get(i).getAttribute("type").equalsIgnoreCase("hidden"))
			{
				String id=input.get(i).getAttribute("id");
				String stepName=id.replaceAll("[\',/'-+.^:,]", "_");
				concatStepName+=stepName+"|";
				String Action=stepName+"_Action";
				concatStepName+=Action+"|";
				concatStepValue+=id+"|";
				concatStepValue+="|";
				logTemplate.print("<Step Name=\"");
				logTemplate.print(stepName);
				logTemplate.print("\">\n<param  Name=\"FrameSrc\"></param>\n<param  Name=\"FindElementById\">");
				logTemplate.print(id);
				logTemplate.print("</param>\n");
				//logTemplate.print("<param  Name=\"FindElementByName\"/> 		<param  Name=\"FindElementByXpath\"/> ");
				logTemplate.print("			<param  Name=\"Action\" event=\"selectdropdown\">");
				logTemplate.print(Action);
				logTemplate.print("</param> 	</Step>");
				
		/*		logTemplate.print("\t"+input.get(i).getAttribute("name"));
				logTemplate.println("\t"+input.get(i).getAttribute("size"));
		*/	}

		}
		
		
		
		//log.println("-End of Org Site-");
		
		
	}
	catch(NoSuchElementException ne)
	{
		System.out.println(ne.getLocalizedMessage());
	}
	catch(UnknownServerException u)
	{
		System.out.println(u.getLocalizedMessage());
	}
		logTemplate.print("</TestCase>");
		logTemplate.close();
		writeLogs(concatStepName,concatStepValue,pageName);
	}
	
	
	
	public static void writeLogs(String concatStepName,String concatStepValue,String pageName)
	{PrintWriter exlLogValue=null;
		try {
			exlLogValue = new PrintWriter(new File(ReadTestSuite.testSuitePath+"/logs/"+"\\Inspect_"+pageName+"_Values_"+new Date().toString().replaceAll(":", "-")+".out"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		exlLogValue.println(concatStepName);
		//System.out.println(concatStepName);
		int lineCount=0;
		while (lineCount<250)
		{
			exlLogValue.println(concatStepValue);
			//System.out.println(concatStepValue);
			lineCount++;
			
		}
		
		
		exlLogValue.close();
		System.out.println("end");
	}
	
	
	
	
	public static void main(String[]a)
	{
		//BrowserSetup br= new BrowserSetup(a[0], a[1], a[2], a[3],a[4]);
	}

}
